/**
 * TODO: 区分环境 —— NODE_ENV
 * - whenDev ☞ process.env.NODE_ENV === 'development'
 * - whenTest ☞ process.env.NODE_ENV === 'test'
 * - whenProd ☞ process.env.NODE_ENV === 'production'
 */
// const CracoLessPlugin = require('craco-less')
const webpack = require('webpack')
const WebpackBar = require('webpackbar')
const FastRefreshCracoPlugin = require('craco-fast-refresh')
const CracoLessPlugin = require('craco-less')
// const CracoAntDesignPlugin = require('craco-antd')
const path = require('path')

const modifiedTheme = {
  // '@primary-color': '#1DA57A'
}

module.exports = {
  webpack: {
    alias: {
      '@': path.join(__dirname, 'src')
    },
    externals: {
      echarts: 'echarts'
    },
    plugins: [
      // webpack构建进度条
      new WebpackBar({ profile: true }),
      // 忽略未引用的文件
      new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
    ],
    //抽离公用模块
    optimization: {
      splitChunks: {
        cacheGroups: {
          commons: {
            chunks: 'initial',
            minChunks: 2,
            maxInitialRequests: 5,
            minSize: 0
          },
          vendor: {
            test: /node_modules/,
            chunks: 'initial',
            name: 'vendor',
            priority: 10,
            enforce: true
          }
        }
      }
    }
  },
  babel: {
    presets: [
      [
        '@babel/preset-env',
        {
          modules: false, // 对ES6的模块文件不做转化，以便使用tree shaking、sideEffects等
          useBuiltIns: 'entry', // browserslist环境不支持的所有垫片都导入
          corejs: {
            version: 3, // 使用core-js@3
            proposals: true
          }
        }
      ]
    ],

    plugins: [
      ['import', { libraryName: 'antd', libraryDirectory: 'es', style: true }, 'antd'],
      ['@babel/plugin-proposal-class-properties', { loose: true }],
      ['@babel/plugin-proposal-decorators', { legacy: true }]
    ]
  },

  plugins: [
    {
      plugin: CracoLessPlugin,
      options: {
        lessLoaderOptions: {
          lessOptions: {
            modifyVars: modifiedTheme,
            javascriptEnabled: true
          }
        }
      }
    },
    {
      plugin: CracoLessPlugin,
      options: {
        modifyLessRule: function (lessRule, _context) {
          lessRule.test = /\.(less)$/
          lessRule.use = [
            {
              loader: 'style-loader'
            },
            {
              loader: 'css-loader',
              options: {
                modules: {
                  localIdentName: '[local]-[hash:5]'
                }
              }
            },
            {
              loader: 'less-loader',
              options: {
                lessOptions: {
                  modifyVars: modifiedTheme,
                  javascriptEnabled: true
                }
              }
            }
          ]
          lessRule.exclude = /node_modules/
          return lessRule
        }
      }
    },
    {
      plugin: FastRefreshCracoPlugin
    }
  ]
}
